<template>
  <div class="add-good">
    <el-form
      ref="addGoodForm"
      :model="addGoodForm"
      :rules="addGoodRules"
      label-position="top"
    >
      <!-- 产品图片、产品名、产品价格、产品秒杀价、产品总量、产品描述、开始时间、结束时间 -->
      <div class="upload-image">
        <el-form-item label="产品图片" prop="good_img">
          <el-upload
            class="image-uploade"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="handleBeforeUpload"
            :headers="headers"
            :on-error="handleUploadError"
            name="file"
          >
            <img
              v-loading="uploadLoading"
              v-if="addGoodForm.good_img"
              :src="addGoodForm.good_img"
              class="image"
            />
            <i v-else class="el-icon-plus image-uploade-icon"></i>
          </el-upload>
        </el-form-item>
      </div>

      <div class="add-good-title">
        <el-form-item label="产品名" prop="good_title">
          <el-input
            type="text"
            maxlength="10"
            placeholder="请输入产品名"
            v-model="addGoodForm.good_title"
          />
        </el-form-item>
      </div>

      <div class="add-good-prices">
        <el-form-item label="产品价格" prop="price">
          <el-input
            type="text"
            placeholder="请输入产品价格"
            v-model="addGoodForm.price"
          />
        </el-form-item>
      </div>

      <div class="add-good-seckill-prices">
        <el-form-item label="秒杀价格" prop="seckill_price">
          <el-input
            type="text"
            placeholder="请输入秒杀价格"
            v-model="addGoodForm.seckill_price"
          />
        </el-form-item>
      </div>

      <div class="add-good-total">
        <el-form-item label="产品总量" prop="total">
          <el-input
            type="text"
            placeholder="请输入产品总量"
            v-model="addGoodForm.total"
          />
        </el-form-item>
      </div>

      <div class="add-good-desc">
        <el-form-item label="产品描述" prop="good_desc">
          <el-input
            type="textarea"
            maxlength="100"
            placeholder="请输入产品描述(小于100字)"
            v-model="addGoodForm.good_desc"
          />
        </el-form-item>
      </div>

      <div class="add-start-time">
        <el-form-item label="开始时间" prop="start_time">
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="addGoodForm.start_time"
              style="width: 100%"
            ></el-date-picker>
          </el-col>
          <el-col :span="11" style="margin-left: 5%">
            <el-time-picker
              placeholder="选择时间"
              v-model="addGoodForm.start_time"
              style="width: 100%"
            ></el-time-picker>
          </el-col>
        </el-form-item>
      </div>

      <div class="add-end-time">
        <el-form-item label="结束时间" prop="end_time">
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="addGoodForm.end_time"
              style="width: 100%"
            ></el-date-picker>
          </el-col>
          <el-col :span="11" style="margin-left: 5%">
            <el-time-picker
              placeholder="选择时间"
              v-model="addGoodForm.end_time"
              style="width: 100%"
            ></el-time-picker>
          </el-col>
        </el-form-item>
      </div>

      <div class="add-button">
        <el-button
          type="primary"
          :loading="addGoodLoading"
          @click="addGood('addGoodForm')"
        >
          <span v-if="!addGoodLoading">添 加</span>
          <span v-else>添 加 中...</span>
        </el-button>
      </div>

      <div class="reset-button">
        <el-button @click="resetForm('addGoodForm')">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { insertGood } from "@/api/good";
import { getToken } from "@/utils/auth";
export default {
  name: "AddGood",
  data() {
    let checkPrice = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("价格不能为空"));
      }
      setTimeout(() => {
        if (isNaN(value)) {
          callback(new Error("请输入数字值"));
        }
      }, 1000);
    };
    let checkTotal = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("产品总量不能为空"));
      }
      setTimeout(() => {
        if (isNaN(value)) {
          callback(new Error("请输入数字值"));
        }
      }, 1000);
    };
    return {
      addGoodLoading: false,
      addGoodForm: {
        good_img: "",
        good_title: "",
        price: "",
        seckill_price: "",
        total: "",
        good_desc: "",
        start_time: "",
        end_time: "",
      },
      addGoodRules: {
        good_img: [
          {
            required: true,
            message: "图片不能为空",
            trigger: "blur",
          },
        ],
        good_title: [
          {
            required: true,
            message: "产品名不能为空",
            trigger: "blur",
          },
        ],
        price: [
          {
            validator: checkPrice,
            trigger: "blur",
          },
        ],
        seckill_price: [
          {
            validator: checkPrice,
            trigger: "blur",
          },
        ],
        total: [
          {
            validator: checkTotal,
            trigger: "blur",
          },
        ],
        good_desc: [
          {
            required: true,
            message: "产品描述不能为空",
            trigger: "blur",
          },
        ],
        start_time: [
          {
            required: true,
            message: "请输入开始时间不能为空",
            trigger: "blur",
          },
        ],
        end_time: [
          {
            required: true,
            message: "请输入结束时间不能为空",
            trigger: "blur",
          },
        ],
      },
      uploadLoading: false,

      uploadUrl: "/api/file/upload",
      headers: {
        tokenAuthorization: "Bearer" + getToken(),
      },
    };
  },
  methods: {
    handleImageSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeImageUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    addGood(formName) {
      // TODO 校验有问题
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //     this.addGoodLoading = true;

      //     insertGood(this.addGoodForm)
      //       .then((res) => {
      //         this.$message.success("添加成功!");
      //         this.addGoodLoading = false;
      //         this.$refs[formName].resetFields();
      //       })
      //       .catch((err) => {
      //         this.addGoodLoading = false;
      //       });
      //   } else {
      //     this.addGoodLoading = false;
      //     return;
      //   }
      // });

      this.addGoodLoading = true;

      insertGood(this.addGoodForm)
        .then((res) => {
          this.$message.success("添加成功!");
          this.addGoodLoading = false;
          this.$refs[formName].resetFields();
        })
        .catch((err) => {
          this.addGoodLoading = false;
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleUploadSuccess(res) {
      this.$message.success("上传成功！");
      this.addGoodForm.good_img = res.data.url;
      this.uploadLoading = false;
    },

    handleBeforeUpload(file) {
      let fileExtension = "";
      if (file.name.lastIndexOf(".") > -1) {
        fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      }

      if (
        fileExtension != "jpg" &&
        fileExtension != "png" &&
        fileExtension != "jpeg"
      ) {
        this.$message.error("上传图片格式不符");
        return false;
      }

      const fileSize = file.size / 1024 / 1024 < 5;
      if (!fileSize) {
        this.$message.error("上传图片大小不能超过 5MB！");
        return false;
      }

      this.uploadLoading = true;
    },

    handleUploadError() {
      this.$message.error("上传失败，请稍后重试");
      this.uploadLoading = false;
    },
  },
};
</script>

<style>
.image-uploade .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-left: 30px;
  margin-top: 10px;
}
.image-uploade .el-upload:hover {
  border-color: #409eff;
}
.image-uploade-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.image {
  width: 200px;
  height: 100px;
  display: block;
}

.el-form-item__label {
  padding-bottom: 0px !important;
}

.add-button,
.reset-button {
  display: inline-block;
  margin-left: 10%;
}

.add-button .el-button,
.reset-button .el-button {
  width: 150px;
  height: 40px;
}
</style>